module ModelSchemaInfo
  require 'model_schema_info/collector/results'

  class Collector
    def initialize(options={})
      @model_klasses = if model_names = options[:model_names].present? ? options[:model_names] : nil
                         [model_names].flatten.map { |model_name| try_find_klass(model_name) }
                       else
                         all_model_class
                       end

    end

    def search_all_models
      model_klasses.each do |klass|
        results.add(klass, klass.reflect_on_all_associations, klass.content_columns)
      end
    end

    def results
      @results ||= ModelSchemaInfo::Results.new
    end

    private

      def model_klasses
        @model_klasses || []
      end

      def try_find_klass(class_name)
        begin
          class_name.classify.constantize
        rescue
          raise NameError, "Error: '#{class_name}' model is not found"
          exit
        end
      end

      # get all model class,
      # but except ActiveRecord::SchemaMigration and dont exist table model
      def all_model_class
        Rails.application.eager_load!
        ActiveSupport::DescendantsTracker.descendants(ActiveRecord::Base).reject do |klass|
          excpet_klass?(klass)
        end
      end

      def excpet_klass?(klass)
        if klass == ActiveRecord::SchemaMigration || klass.inspect.include?("Table doesn't exist")
          true
        else
          false
        end
      end

  end

end
